<?php
// +----------------------------------------------------------------------
// | Azthink通用开发平台 [ TOMORROW IS ANOTHER DAY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2019 http://www.azthink.top All rights reserved.
// +----------------------------------------------------------------------
// | Author 李忠<azthink@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\model;

use think\Exception;
use think\Model;

/**
 * 文件模型
 * @author 李忠<azthink@qq.com>
 * @createAt 2018-09-12 16:08:42
 */
class File extends Model {
    // 设置当前模型对应的完整数据表名称
    protected $table = '__SYS_FILE__';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    public function getSizeTextAttr($value, $data) {
        return round($data['size'] / 1024);
    }


    //自定义方法
    public static function lists($name) {
        $map = array();
        if ($name !== '' && !empty($name)) {
            array_push($map, ['a.name', 'like', '%' . $name . '%']);
        }
        return self::alias('a')->where($map)->order('a.id desc')->paginate();
    }

    public static function upload($file, $setting) {
        /* 检测文件是否存在 */
        $isData = self::isFile(['md5' => $file->hash('md5'), 'sha1' => $file->hash()]);

        if ($isData) {
            return $isData; //文件上传成功
        }

        $info = $file->validate(['ext' => $setting['ext'], 'size' => $setting['size']])
            ->rule($setting['save_name'])->move($setting['upload_path'], true, $setting['replace']);

        if ($info) {
            /* 记录文件信息 */
            $data['name'] = $info->getInfo('name');
            $data['savename'] = $info->getBasename();
            $data['savepath'] = $setting['upload_path'] . basename($info->getPath()) . '/';
            $data['ext'] = $info->getExtension();
            $data['mime'] = $info->getInfo('type');
            $data['size'] = $info->getInfo('size');
            $data['md5'] = $file->hash('md5');
            $data['sha1'] = $file->hash('sha1');
            $data['location'] = 0;
            $data['create_time'] = time();
            if ($add = self::create($data)) {
                $data['id'] = $add->id;
            }
            return $data; //文件上传成功
        } else {
            throw new Exception($file->getError());
        }

    }

    /**
     * 检测当前上传的文件是否已经存在
     * @param  array $file 文件上传数组
     * @return boolean       文件信息， false - 不存在该文件
     */
    public static function isFile($file) {
        if (empty($file['md5'])) {
            throw new \Exception('缺少参数:md5');
        }
        /* 查找文件 */
        $map = ['md5' => $file['md5'], 'sha1' => $file['sha1']];
        if ($data = self::where($map)->find()) {
            return $data->toArray();
        } else {
            return false;
        }
    }


}
